<template>
  <n-modal
    :show="show"
    :show-mask="false"
    :mask-closable="true"
    :auto-focus="false"
    :closable="false"
    class="gift-history-modal"
    @update:show="onUpdateShow"
  >
    <div class="history-card">
      <div class="close-btn" @click="close"></div>
      <h2 class="title">打赏记录</h2>

      <n-spin :show="loading">
        <n-data-table
          :columns="columns"
          :data="rows"
          :bordered="false"
          :single-line="false"
          size="large"
          class="history-table"
          table-layout="fixed"
          :render-empty="renderEmpty"
        />
      </n-spin>


    </div>
  </n-modal>
</template>

<script setup lang="ts">
import { ref, watch, h } from 'vue'
// 使用原生 Date，不引入 dayjs
import { get } from '@/utils/common/request'
import { useEnvStore } from '@/store'
import { NEmpty } from 'naive-ui'
import type { DataTableColumn } from 'naive-ui'

const props = defineProps({
  show: { type: Boolean, default: false }
})
const emit = defineEmits(['update:show'])
function onUpdateShow(v: boolean) { emit('update:show', v) }
function close() { emit('update:show', false) }

const loading = ref(false)

// 列定义：打赏时间、打赏渠道、打赏员工、礼物名称、打赏金额
const columns: DataTableColumn[] = [
  { title: '打赏时间', key: 'time', align: 'center' },
  { title: '打赏渠道', key: 'channel', align: 'center' },
  { title: '打赏员工', key: 'employee', align: 'center' },
  { title: '礼物名称', key: 'giftName', align: 'center' },
  { title: '打赏金额', key: 'amount', align: 'center' }
]

interface RowItem {
  time: string
  channel: string
  employee: string
  giftName: string
  amount: string | number
}

const rows = ref<RowItem[]>([])

const envStore = useEnvStore()

async function fetchRecords() {
  try {
    loading.value = true
    const placeId = envStore.placeInfo?.placeId as any
    const idNumber = envStore.userInfo?.idNumber as any

    const res: any = await get('/marketing-server/client/giftRewarding/findDetailByPlaceIdAndIdNumber', {
      params: { placeId, idNumber }
    })
    const raw = res?.data ?? res
    const list = Array.isArray(raw?.list)
      ? raw.list
      : (Array.isArray(raw) ? raw : (raw ? [raw] : []))

    rows.value = list.map((it: any) => ({
      time: formatTime(it.created),
      channel: '客户端',
      employee: it.accountName ?? '-',
      giftName: it.giftName + '*' + it.giftCount,
      amount: formatAmount(Number(it.giftCount ?? 0) * Number(it.giftMoney ?? 0) / 100)
    }))
  } catch (e) {
    console.error('fetch gift history error:', e)
  } finally {
    loading.value = false
  }
}
const dateTextTransfer = (dateText: string) => {
  return +dateText < 10 ? `0${dateText}` : dateText;
};


function formatTime(cellValue: any) {
    if (!cellValue) return '';
    const month = dateTextTransfer(cellValue[1]);
    const day = dateTextTransfer(cellValue[2]);
    const hour = dateTextTransfer(cellValue[3]);
    const minute = dateTextTransfer(cellValue[4]) || '00';
    const second = dateTextTransfer(cellValue[5]) || '00';
    return `${cellValue[0]}-${month}-${day} ${hour}:${minute}:${second}`;
  }

function formatAmount(v: any) {
  const n = Number(v)
  return isNaN(n) ? String(v) : `${n.toFixed(2)} 元`
}

const renderEmpty = () => h(NEmpty, { description: '暂无数据' })

watch(() => props.show, (val) => {
  if (val) fetchRecords()
}, { immediate: false })
</script>

<style scoped lang="scss">
.gift-history-modal {
  display: grid;
  place-items: center;
}

.history-card {
  position: relative;
  width: 860px;
  background: #fff;
  border-radius: 28px;
  padding: 36px 40px 28px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.18);
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: 800;
  margin: 8px 0 16px;
  color: #000;
}

.close-btn {
  position: absolute;
  right: 18px;
  top: 18px;
  width: 28px;
  height: 28px;
  background: url('@/assets/gb2.png') no-repeat center / cover;
  cursor: pointer;
  transition: transform .2s ease;
}
.close-btn:hover { transform: scale(1.06) rotate(180deg); }

.history-table {
  margin-top: 12px;
  width: 100%;
}
:deep(.n-data-table) {
  width: 100%;
}

/* 表头参考效果：深灰圆角胶囊 */
:deep(.n-data-table-th) {
  background: #3b3b3b;
  color: #fff;
  border-color: transparent;
}
:deep(.n-data-table-tr:first-child .n-data-table-th:first-child) {
  border-top-left-radius: 28px;
  border-bottom-left-radius: 28px;
}
:deep(.n-data-table-tr:first-child .n-data-table-th:last-child) {
  border-top-right-radius: 28px;
  border-bottom-right-radius: 28px;
}

/* 去掉多余边框与阴影，靠近设计图 */
:deep(.n-data-table-table) {
  box-shadow: none;
}

.empty-hint {
  text-align: center;
  color: #777;
  margin-top: 16px;
}
</style>